package com.whu.MenuHub.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whu.MenuHub.domain.Order;
import com.whu.MenuHub.domain.OrderDTO;
import com.whu.MenuHub.domain.User;
import com.whu.MenuHub.exception.MenuHubException;
import com.whu.MenuHub.service.OrderService;
import com.whu.MenuHub.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/orders")
@Api(tags = "订单管理API")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;


    //把userID作为参数，要判断权限
    @GetMapping("/detail/{id}/{userID}")
    @ApiOperation("根据订单id获取订单信息")
    @PreAuthorize("hasAnyAuthority('all',#userID.toString())")
    public OrderDTO getOrderDetailByOrderID(@ApiParam("订单ID")@PathVariable Integer id,
                                            @ApiParam("用户ID")@PathVariable Integer userID)throws MenuHubException{
        OrderDTO orderDTO= orderService.getOrderDetailByOrderID(id);
        User searchUser=userService.getUserByUserID(userID);
        if(searchUser.getId()!=userID&&searchUser.getRole()!="owner"){
            throw new MenuHubException(MenuHubException.ErrorType.QUERY_ERROR,"没有权限查找该订单信息");
        }
        else return orderDTO;
    }

    //用户只能获取到用户对应的订单信息
//    @GetMapping("/userID/{userID}")
//    @ApiOperation("根据用户id获取订单信息")
//    @PreAuthorize("hasAnyAuthority('all',#userID.toString())")
//    public IPage<Order> getOrderByUserID(@ApiParam("用户ID")@PathVariable Integer userID,
//                                                     @ApiParam("页码")@RequestParam(defaultValue = "0")Integer pageNum,
//                                                     @ApiParam("每页记录数") @RequestParam(defaultValue = "10")Integer pageSize){
//        Map<String,Object> condition=new HashMap<>();
//        condition.put("userID",userID);
//
//        return orderService.getOrders(condition, pageNum,pageSize);
//
//    }

    //获取订单信息，返回订单的基本信息, 用户只能获取到用户对应的订单信息,商家可以获取到全部信息
    @GetMapping("")
    @ApiOperation("根据条件获取订单信息")
    @PreAuthorize("hasAnyAuthority('all',#userID.toString())")
    public IPage<Order> getOrders(@ApiParam("用户ID")@RequestParam(value = "userID") Integer userID,
                                  @ApiParam("排序字段")@RequestParam(value = "orderField",required = false) String orderField,
                                  @ApiParam("排序类型")@RequestParam(value = "orderType",required = false) String orderType,
                                  @ApiParam("类似评论")@RequestParam(value = "comment",required = false) String comment,
                                  @ApiParam("页码")@RequestParam(defaultValue = "0")Integer pageNum,
                                  @ApiParam("每页记录数") @RequestParam(defaultValue = "10")Integer pageSize,
                                  @ApiParam("订单状态")@RequestParam(value = "state",required = false)String state){
        Map<String,Object> condition=new HashMap<>();
        if(userID!=null) {
            User user=userService.getUserByUserID(userID);
            if(user.getRole().equals("customer")){
                condition.put("userID",userID);
            }
        }
        if(orderType!=null) {
            condition.put("orderType",orderType);
        }
        if(comment!=null) {
            condition.put("comment",comment);
        }
        if(state!=null) {
            condition.put("state",state);
        }
        //判断是否需要排序，排序的方式
        if(orderField!=null&&(orderField.equals("tasteScore")||orderField.equals("serviceScore")||orderField.equals("environmentScore"))) {
            condition.put("orderField",orderField);
        }
        return orderService.getOrders(condition, pageNum,pageSize);

    }

    //新增订单信息，可以将订单中的食物一起传递
    @PostMapping("")
    @ApiOperation("新增一条订单记录")
    @PreAuthorize("hasAnyAuthority('all',#orderDTO.userID)")
    public Order InsertOrder(@ApiParam("订单信息")@RequestBody OrderDTO orderDTO) throws MenuHubException {
        orderDTO.setHasRejected(false);
        return orderService.insertOrder(orderDTO);
    }

    @PutMapping("")
    @ApiOperation("修改一条订单记录")
    @PreAuthorize("hasAnyAuthority('all',#orderdto.userID)")
    public void updateOrder(@ApiParam("订单信息")@RequestBody OrderDTO orderdto) throws MenuHubException {
        System.out.println("修改订单记录");
       orderService.updateOrderComment(orderdto);
    }

    @PutMapping("/state")
    @ApiOperation("修改一条订单记录")
    @PreAuthorize("hasAnyAuthority('all')")
    public void updateOrderState(@ApiParam("订单状态")@RequestBody Order order ) throws MenuHubException {
        //返回的照片已经修改 所以在更新状态的时候需要重新设置
        order.setPhoto(orderService.getById(order.getId()).getPhoto());
        orderService.updateOrderByID(order);
    }


    //删除订单记录，会把食品评价表中的记录一起删除
    @DeleteMapping("/{id}/{userID}")
    @ApiOperation("删除一条订单记录")
    @PreAuthorize("hasAnyAuthority('all',#userID.toString())")
    public void deleteUser(
            @ApiParam("订单ID")@PathVariable Integer id,
            @ApiParam("用户ID")@PathVariable Integer userID) throws MenuHubException {
        orderService.deleteOrderbyOrderID(id);
    }

    //处理订单评价
//    @PutMapping("comment")
//    @ApiOperation("修改一条订单记录")
//    @PreAuthorize("hasAnyAuthority(#order.userID)")
//    public void updateOrderComment(@ApiParam("订单信息")@RequestBody OrderDTO orderDTO) throws MenuHubException {
//        //orderService.updateOrderByID(orderDTO);
//    }
    @GetMapping("/price/{dayNum}")
    @ApiOperation("获取期限内的订单总额")
    Float getPriceByTime(@PathVariable int dayNum){
        return orderService.getPriceByTime(dayNum);
    }

    @GetMapping("/orderNum/{dayNum}")
    @ApiOperation("获取期限内的订单数量")
    Integer getOrderNumByTime(@PathVariable int dayNum){
        return orderService.getOrderNumByTime(dayNum);
    }
}
